package dw.fastfile.common.dto.sync;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @description: 同步公共代码表的参照
 * @author: wanghao
 * @create: 2022-06-28 15:07
 **/
public abstract class AbstractSyncComRefData extends AbstractSyncRefData {

    @Override
    protected String getSourceTableName() {
        return "ss_cfp_cd";
    }

    @Override
    protected String sourceCodeField() {
        return "cd_val";
    }

    @Override
    protected String sourceNameField() {
        return "cd_desc";
    }

    /**
     * 公共代码表的编码
     *
     * @return
     */
    protected abstract String sourceCodeNo();

    @Override
    protected String getSaveDataSql() {
        return new StringBuilder("select cd_val,cd_desc from ss_cfp_cd  where 1=1 and enable_flg = 1 ")
                .append(" and cd_no = '" + this.sourceCodeNo() + "' ")
                .append(" and cd_val not in  ")
                .append(" (select code from ").append(this.getTargetTableName()).append(" ) ")
                .append(" order by cd_val ")
                .toString();
    }

    @Override
    protected String getUpdateDataSql() {
        return "SELECT DISTINCT \n" +
                "r.cd_val,r.cd_desc\n" +
                "FROM " + this.getSourceTableName() + " r," + this.getTargetTableName() + " t\n" +
                "WHERE 1=1 \n" +
                "AND r.enable_flg = 1\n" +
                "AND r.cd_no = '" + this.sourceCodeNo() + "'\n" +
                "AND r.cd_val = t.code\n" +
                "AND r.cd_desc <> t.name";
    }

    @Override
    protected void updateTarget(JdbcTemplate jdbcTemplate, RefData ref) {
        String updateDataSql = "UPDATE chinasoftinc_db." + this.getTargetTableName() +
                " SET name = " + "'" + ref.getName() + "'" +
                " WHERE code = " + "'" + ref.getCode() + "'";

        jdbcTemplate.update(updateDataSql);
    }

}
